﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Client;
using SiemensOPC;
using VswService_V7.Config;
using VswService_V7.DataBase.Tables;
using System.Data;
using VswService_V7.Utility;

namespace VswService_V7.OPC.DB
{
    public class Fn1PipeEventAddressDbData : SubscriptionDbDataBase
    {
        List<string> pipeInformationList;
        BasicPipeInfo pipeInfo;
        CheckMinDelay askTimeCheck;
        public Fn1PipeEventAddressDbData(SimaticOPCClient opc, NodeConfig nodes) : base(opc, nodes)
        {
            pipeInformationList = new List<string>();
            pipeInfo = new BasicPipeInfo();
            askTimeCheck = new CheckMinDelay(2);
        }
        public override void CreateSubscription()
        {
            try
            {
                opcServer.QuickAddMonitorItem(opcNodes.PipeEventAddress1.GrpoupName,
                    opcNodes.PipeEventAddress1.PublishTime,
                    opcNodes.PipeEventAddress1.SampleTime,
                    opcNodes.PipeEventAddress1.GetNodeAddress(),
                    opcNodes.PipeEventAddress1.GetNodeDisplayName(),
                    SubscriptionHandlerAsk);

                opcServer.QuickAddMonitorItem(opcNodes.PipeEventDataAddress1.GrpoupName,
                    opcNodes.PipeEventDataAddress1.PublishTime,
                    opcNodes.PipeEventDataAddress1.SampleTime,
                    opcNodes.PipeEventDataAddress1.GetNodeAddress(),
                    opcNodes.PipeEventDataAddress1.GetNodeDisplayName(),
                    SubscriptionHandlerStripNo);

                opcServer.QuickAddMonitorItem(opcNodes.PipeDataAddress1.GrpoupName,
                    opcNodes.PipeDataAddress1.PublishTime,
                    opcNodes.PipeDataAddress1.SampleTime,
                    opcNodes.PipeDataAddress1.GetNodeAddress(),
                    opcNodes.PipeDataAddress1.GetNodeDisplayName(),
                    SubscriptionHandlerRspData);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        private void SubscriptionHandlerAsk(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
            if (notification == null || notification.Value.Value == null)
                return;
            if (monitoredItem.DisplayName == "PipeInfoAsk")
            {
				Console.WriteLine("PipeInfoAsk");
				bool ask = false;
                if (bool.TryParse(notification.Value.Value.ToString(), out ask))
                {
                    if (ask)
                    {						
						Console.WriteLine("PipeInfoAsk=true");
						if (askTimeCheck.ActionVaild())
							Task.Run(() => HandleNewAsk());
					}
                    else
                    {
                        opcServer.WriteValue("false", opcNodes.PipeEventAddress1.PipeInfoRsp);
						Console.WriteLine("PipeInfoRsp=false");
					}
                }
            }
        }

        private void SubscriptionHandlerStripNo(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
            if (notification == null || notification.Value.Value == null)
                return;

            if (monitoredItem.DisplayName == "Batch_No")
            {
                pipeInfo.batchNumber = notification.Value.Value.ToString();
				Console.Write(pipeInfo.batchNumber);
            }

            if (monitoredItem.DisplayName == "Pipe_No")
            {
                pipeInfo.pipeNumber = notification.Value.Value.ToString();
				Console.Write(pipeInfo.pipeNumber);
			}
        }

        private async Task  HandleNewAsk()
        {
            await Task.Delay(1000);
            try
            {
                DataTable pipeTable = PIPE_INFO.SelectLastTimePipe(pipeInfo.GetFullPipeNumber());
                if (pipeTable != null && pipeTable.Rows.Count > 0)
                {
                    string stripNo = pipeTable.Rows[0][PIPE_INFO.fd_stripNo].ToString();
                    DataTable stripTable = STRIP_INFO.SelectStripInfo(stripNo);
                    if (stripTable != null && stripTable.Rows.Count > 0)
                    {
                        string taskNo = pipeTable.Rows[0][PIPE_INFO.fd_taskNo].ToString();
                        DataTable taskTable = TASK_INFO.SelectTaskInfo(taskNo);
                        if (taskTable != null && taskTable.Rows.Count > 0)
                        {
                            string qc_code = pipeTable.Rows[0][PIPE_INFO.fd_qualityCode].ToString();
                            string qc_low = "65535";
                            string qc_high = "65535";
                            if(qc_code.Length>5)
                            {
                                qc_low = qc_code.Substring(qc_code.Length - 5, 5);
                                qc_high = qc_code.Substring(0,qc_code.Length - 5);
                            }
                            else
                            {
                                qc_low = qc_code;
                                qc_high = "0";
                            }
                            pipeInformationList.Clear();
                            pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_taskNo].ToString());


                            //if(!string.IsNullOrEmpty(stripTable.Rows[0][STRIP_INFO.fd_isSpy].ToString()) && int.TryParse(stripTable.Rows[0][STRIP_INFO.fd_isSpy].ToString(),out int r))
                            //{
                            //    pipeInformationList.Add(stripTable.Rows[0][STRIP_INFO.fd_isSpy].ToString());
                            //}
                            //else
                            //{
                            //    pipeInformationList.Add("0");

                            //}
                            pipeInformationList.Add("0");


                            //if (!string.IsNullOrEmpty(stripTable.Rows[0][STRIP_INFO.fd_stripDurabilityClass].ToString()) && int.TryParse(stripTable.Rows[0][STRIP_INFO.fd_stripDurabilityClass].ToString(), out int r1))
                            //{
                            //    pipeInformationList.Add(stripTable.Rows[0][STRIP_INFO.fd_stripDurabilityClass].ToString());
                            //}
                            //else
                            //{
                            //    pipeInformationList.Add("0");

                            //}
                            pipeInformationList.Add("0");


                            pipeInformationList.Add(Formats.ConvertUnit(stripTable.Rows[0][STRIP_INFO.fd_stripThk].ToString(), VswUnit.STRIP_THK_L1,0));


                            //if (!string.IsNullOrEmpty(stripTable.Rows[0][STRIP_INFO.fd_stripSteelGrade].ToString()) && int.TryParse(stripTable.Rows[0][STRIP_INFO.fd_stripSteelGrade].ToString(), out int r2))
                            //{
                            //    pipeInformationList.Add(stripTable.Rows[0][STRIP_INFO.fd_stripSteelGrade].ToString());
                            //}
                            //else
                            //{
                            //    pipeInformationList.Add("0");

                            //}
                            pipeInformationList.Add("0");

                            pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeNominalLength].ToString(), VswUnit.PIPE_LENGTH_L1, 0));
                            pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMaxLength].ToString(), VswUnit.PIPE_LENGTH_L1, 0));
                            pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMinLength].ToString(), VswUnit.PIPE_LENGTH_L1, 0));
                            pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeNominalOd].ToString(), VswUnit.PIPE_OD_L1,0));
                            pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMaxOd].ToString(), VswUnit.PIPE_OD_L1,0));
                            pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMinOd].ToString(), VswUnit.PIPE_OD_L1,0));
                            pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeNominalThickness].ToString(), VswUnit.PIPE_WT_L1,0));
                            pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMinThickness].ToString(), VswUnit.PIPE_WT_L1,0));


                            //if (!string.IsNullOrEmpty(taskTable.Rows[0][TASK_INFO.fd_innerBeadIsremoving].ToString()) && int.TryParse(taskTable.Rows[0][TASK_INFO.fd_innerBeadIsremoving].ToString(), out int r3))
                            //{
                            //    pipeInformationList.Add(taskTable.Rows[0][TASK_INFO.fd_innerBeadIsremoving].ToString());
                            //}
                            //else
                            //{
                            //    pipeInformationList.Add("0");

                            //}
                            pipeInformationList.Add("0");
                            //pipeInformationList.Add(taskTable.Rows[0][TASK_INFO.fd_innerBeadIsremoving].ToString());

                            //pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_innerBeadHeight].ToString(), VswUnit.INNER_BEAD_HEIGHT_L1,0));
                            pipeInformationList.Add("0");

                            //pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_innerBeadDepth].ToString(), VswUnit.INNER_BEAD_Depth_L1,0));
                            pipeInformationList.Add("0");

                            //pipeInformationList.Add(taskTable.Rows[0][TASK_INFO.fd_ovalityUpLimit].ToString());
                            pipeInformationList.Add("0");

                            //pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_bodyStraightness].ToString(), VswUnit.STRAIGHTNESS_L1,0));
                            pipeInformationList.Add("0");

                            //pipeInformationList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_endStraightness].ToString(), VswUnit.STRAIGHTNESS_L1,0));
                            pipeInformationList.Add("0");

                            pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_stripNo].ToString());
                            pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_stripSeq].ToString());
                            pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_dtj].ToString());
                            pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_length].ToString());
                            pipeInformationList.Add(qc_low);
                            pipeInformationList.Add(qc_high);

                            //pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_sampleReason].ToString());
                            pipeInformationList.Add("0");

                            //pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_sampleFltLength].ToString());
                            pipeInformationList.Add("0");

                            //pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_mechanicalLength].ToString());
                            pipeInformationList.Add("0");

                            //pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_additionalLength].ToString());
                            pipeInformationList.Add("0");

                            pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_headCut].ToString());
                            pipeInformationList.Add(pipeTable.Rows[0][PIPE_INFO.fd_tailCut].ToString());
                        }
                    }
                }

                if (pipeInformationList.Count == opcNodes.PipeDataAddress1.GetNodeAddress().Count)
                {
					opcServer.WriteValues(pipeInformationList, opcNodes.PipeDataAddress1.GetNodeAddress());					
                }
                else
                {
                    List<string> errorList = new List<string>();
                    for (int i = 0; i < opcNodes.PipeDataAddress1.GetNodeAddress().Count; i++)
                        errorList.Add("-1");
                    opcServer.WriteValues(errorList, opcNodes.PipeDataAddress1.GetNodeAddress());
				}
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("HandleNewAsk", ex);
            }
            opcServer.WriteValue("true", opcNodes.PipeEventAddress1.PipeInfoRsp);
		}

        private void SubscriptionHandlerRspData(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
            if (notification == null || notification.Value.Value == null)
                return;
        }
    }

    public class BasicPipeInfo
    {
        public BasicPipeInfo()
        {
            taskNumber = "0";
            stripNumber = "0";
            batchNumber = "0";
            pipeNumber = "0";
            pipeSequence = "0";
            qualityCode = "0";
        }

        public string taskNumber;
        public string stripNumber;
        public string batchNumber;
        public string pipeNumber;
        public string pipeSequence;
        public string qualityCode;

        public string GetFullPipeNumber()
        {
            int pipeNum = int.Parse(pipeNumber);
            string fullPipeNumber = batchNumber + pipeNum.ToString("000");
            return fullPipeNumber;
        }
    }

}
